<?php

class TranslateController extends Controller {
	
	public $models = array("News", "Games", "Gallery", "Pages", "Translate");
	
	private function _save($entity, $id, $lang) {
		$status = 1;
		$message = "OK";
		
		$this->Translate->delete(array("entity_id"=>$id, "lang"=>$lang));
		foreach ($this->data as $k=>$v) {
			$this->Translate->debug = true;
			$ret = $this->Translate->insert(array(
				"entity"	=>$entity,
				"entity_id"	=> $id,
				"entity_field" => $k,
				"translate" => $v,
				"lang" => $lang
			));
			if(!$ret) {
				$status = 0;
				$message = $this->Translate->getErrorMessage();
				break;
			}
		}
		header("X-Translate-Status: $status");
		echo $message;
	}
	
	private function _get($entity, $id, $lang) {
		$translate = $this->Translate->get($lang, $entity, $id);
		$translate["id"] = $id;
		$translate["lang"] = $lang;
		$this->assign("translate", $translate);
	}
	
	public function news($id, $lang=null) {
		if($id) {
			if($this->data) {
				$this->_save("news", $id, $lang);
			}else{
				$this->_get("news", $id, $lang);
				
				$original = $this->News->findRow("*", array("id"=>$id));
				$this->assign("original", $original);
				
				$this->display("admin/news/translate.html", false);
			}
		}
	}
	
	public function games($id, $lang=null) {
		if($id) {
			if($this->data) {
				$this->_save("games", $id, $lang);
			}else{
				$this->_get("games", $id, $lang);
				
				$original = $this->Games->findRow("*", array("id"=>$id));
				$this->assign("original", $original);
				
				$this->display("admin/games/translate.html", false);
			}
		}
	}
	
	public function gallery($id, $lang=null) {
		if($id) {
			if($this->data) {
				$this->_save("gallery", $id, $lang);
			}else{
				$this->_get("gallery", $id, $lang);
				
				$original = $this->Gallery->findRow("*", array("id"=>$id));
				$this->assign("original", $original);
				
				$this->display("admin/gallery/translate.html", false);
			}
		}
	}
	
	public function pages($id, $lang=null) {
		if($id) {
			if($this->data) {
				$this->_save("pages", $id, $lang);
			}else{
				$this->_get("pages", $id, $lang);
				
				$original = $this->Pages->findRow("*", array("id"=>$id));
				$this->assign("original", $original);
				
				$this->display("admin/pages/translate.html", false);
			}
		}
	}
	
}

?>